package mvc.controller;

import com.google.gson.Gson;
import mvc.model.pojos.UserBean;
import mvc.model.service.LoginService;
import mvc.model.service.impl.LoginServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /* request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");*/
        String uname = request.getParameter("uname");
        String upass = request.getParameter("upass");
        System.out.println(uname+":"+upass);
        LoginService loginService = new LoginServiceImpl();
        UserBean userBean = loginService.login(uname, upass);
        Gson gson = new Gson();
        if (userBean != null) {
            Cookie name = new Cookie("uname", userBean.getUname());
            Cookie pass = new Cookie("upass", userBean.getUpass());
            response.addCookie(name);
            response.addCookie(pass);
            request.getSession().setAttribute("user", userBean);
        }
        response.getWriter().append(gson.toJson(userBean, UserBean.class));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (request.getSession().getAttribute("user") != null) {
            response.sendRedirect("center");
        } else {
            response.sendRedirect("login.jsp");
        }
    }
}
